﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TripsLogic.controller;
using TripsLogic.WeSStatus;
using System.Data;
using TripsLogic.util;

namespace TripsLogic
{
    public partial class reset_activated_code : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                loadLang();
            }
        }

        private void loadLang()
        {
            this.litEmail.Text = LangController.getLng("litEmail.Text", "Email");
            this.litResetActivatedCode.Text = LangController.getLng("litResetActivatedCode.Text", "Reset activated code");
            this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + this.litResetActivatedCode.Text;
            this.lbtSend.Text = LangController.getLng("litSend.Text", "Send");
            this.reqValEmail.ErrorMessage = LangController.getLng("litRequired.Text", "(*)");
            this.rgeValEmail.ErrorMessage = LangController.getLng("litInvalidFormat.Text", "Invalid format");
        }

        protected void lbtSend_Click(object sender, EventArgs e)
        {
            WeSSysUser.WeSSysUserClient client = new WeSSysUser.WeSSysUserClient();
            WeSSysUser.CheckAccountResult result = client.checkAccount(txtEmail.Text);
            if (!(result.sysUserResultStatus.statusCode == CheckAccountResult.STATUS_UNAVAILABLE_CODE))
            {
                this.lblEmailResponse.ForeColor = System.Drawing.Color.Red;
                this.lblEmailResponse.Text = LangController.getLng("litNonExistAccount.Text", "Non-existed account");
                this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + this.lblEmailResponse.Text;
            }
            else
            {
                WeSSysUser.ResetActivatedTokenResult result2 =  client.resetActivatedToken(txtEmail.Text);
                if (result2.sysUserResultStatus.statusCode == ResetActivatedTokenResult.STATUS_VALID_RESET_CODE)
                {
                    resetActivatedTokenResponse.Visible = true;
                    contactform.Visible = false;
                    bool sendResult = sendResetActivatedTokenEmail(txtEmail.Text, result2.token);
                    if (sendResult)
                    {
                        this.litResetActivatedTokenResponse.Text = String.Format(LangMsgController.getLngMsg("litResetActivatedTokenResponse.OK", "An email which contains new activated code has been sent to <font style='font-weight:bold'><u>{0}</u></font>. Check email inbox to activate your accountHãy kiểm tra email của bạn."), txtEmail.Text);
                        this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litResetActivatedTokenResponse.OK", "Gửi lại mã xác nhận thành công");
                    }
                    else
                    {
                        this.litResetActivatedTokenResponse.Text = LangMsgController.getLngMsg("litResetActivatedTokenResponse.Error", "Error occurs in the reseting activated code progress.<br/> Please try again later.");
                        this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litResetActivatedTokenResponse.Error", "Error occurs in the reseting activated code progress.");
                    }
                }
                else if (result.sysUserResultStatus.statusCode == ResetActivatedTokenResult.STATUS_ALREADY_ACTIVATED_USER_CODE)
                {
                    this.lblEmailResponse.ForeColor = System.Drawing.Color.Red;
                    this.lblEmailResponse.Text = result.sysUserResultStatus.statusText;
                    this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + result.sysUserResultStatus.statusText;
                }
                else
                {
                    resetActivatedTokenResponse.Visible = true;
                    contactform.Visible = false;
                    this.litResetActivatedTokenResponse.Text = LangMsgController.getLngMsg("litResetActivatedTokenResponse.Error", "Error occurs in the reseting activated code progress.<br/> Please try again later.");
                    this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litResetActivatedTokenResponse.Error", "Error occurs in the reseting activated code progress.");
                }
            }
            client.Close();
        }

        private bool sendResetActivatedTokenEmail(string email, string randomString)
        {
            try
            {
                string resetPasswordEmailTemplate = TemplateController.getTemplate("EMAIL_RESETACTIVATEDTOKEN_TEMP", "<p><font style='font-weight:bold'>TripsLogic</font> - New activated code</p>" +
                        "<p><strong>Email:</strong> {0}</p>" +
                        "<p>To activate your account at <font style='font-weight:bold'>TripsLogic</font>, click on the link below:<br/>{1}</p><br/>" +
                        "<p>This message has been sent from website <font style='font-weight:bold'>TripsLogic</font></p>" +
                        "<p><font style='font-weight:bold'>TripsLogic Team</font></p>");

                DataTable dt = SysUserController.getUserByEmail(email);

                string newActivatedUrl = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/')) +
                  "/activate-" + dt.Rows[0]["Id"].ToString() + "-" + Common.generateHash(email + randomString);
                Common.sendEmail(txtEmail.Text, "", "", "", LangController.getLng("litResetActivatedTokenEmail.Subject", "[TripsLogic] New activated code"),
                    String.Format(resetPasswordEmailTemplate, email, newActivatedUrl), "");

                return true;
            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error sendResetActivatedTokenEmail "));
                return false;
            }
        }
    }
}